//
//  GSDKWebViewController.m
//  GameSDK
//
//  Created by Johnny on 2017/8/7.
//  Copyright © 2017年 Johnny. All rights reserved.
//

#import "GSDKWebViewController.h"
#import "GSDKCommonMethod.h"
#import "Masonry.h"
#import "GSDKComplatformBase.h"
#import "GSDKSuspensionView.h"
#import "GSDKActivityIndicatorView.h"
#import "YYKit.h"
#import "UIAlertView+Extension.h"
#import "NSString+Extension.h"

typedef enum PayState: NSUInteger {
    PayStateCancel,
    PayStateSuccess,
    PayStateFailure
} PayState;

@interface GSDKWebViewController () <UIWebViewDelegate>
@property PayState payState;
@property (nonatomic, strong) UIActivityIndicatorView * aiView;
@property (nonatomic, copy) NSString * urlString;
@property (nonatomic, strong) UIButton * cancelButton;

@property (nonatomic, strong) NSTimer * timer;
@end

@implementation GSDKWebViewController
- (void)dealloc {
    DEBUGMSG(@"GSDKWebViewController dealloc");
    
    [_webView loadRequest:[[NSURLRequest alloc]initWithURL: [NSURL URLWithString:@""]]];
    [_webView removeFromSuperview];
    _webView = nil;
    _webView.delegate = nil;
    [_webView stopLoading];
    
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies]){
        [storage deleteCookie:cookie];
    }
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
    
    if (self.timer != nil) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.payState = PayStateCancel;
    
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, [GSDKCommonMethod getWidth], [GSDKCommonMethod getHight])];
    [self.view addSubview:_webView];
    _webView.backgroundColor = [UIColor whiteColor];
    _webView.delegate = self;
    _webView.scalesPageToFit = YES;
    _webView.autoresizesSubviews = YES;
    _webView.scrollView.alwaysBounceVertical = NO;
    _webView.scrollView.alwaysBounceHorizontal = NO;
    _webView.scrollView.bounces = NO;
    
    _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.right.equalTo(@0);
    }];
    
    _aiView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _aiView.center = CGPointMake([GSDKCommonMethod getWidth]/2, [GSDKCommonMethod getHight]/2);
    _aiView.color = [UIColor colorWithHexString:@"#0197d2"];
    [self.view addSubview:_aiView];
    
    NSString * urlString = GSDKCOMMONMETHOD.versionModel.is_purl;
    if (urlString == nil || urlString.length == 0) { urlString = @"http://api.zy1game.com/api/ocean_payment"; }
    if (![urlString hasSuffix:@"?"]) { urlString = [NSString stringWithFormat:@"%@?", urlString]; }
    
    if ([self.urlString rangeOfString:urlString].length > 0) {
        _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        if (iPhoneX) {
            [_cancelButton setFrame:CGRectMake([GSDKCommonMethod getWidth] - 42 - 40, 20, 26, 26)];
        } else {
            [_cancelButton setFrame:CGRectMake([GSDKCommonMethod getWidth] - 42, 20, 26, 26)];
        }
        [_cancelButton setBackgroundImage:[UIImage imageNamed:@"ZYSDK_Resourcres.bundle/pic/icon_tabbar_cancel.png"] forState:UIControlStateNormal];
        [self.view addSubview:_cancelButton];
        
        [_cancelButton addTarget:self action:@selector(payCancelAction) forControlEvents:UIControlEventTouchUpInside];
    }
    
    self.timer = [NSTimer timerWithTimeInterval:15 block:^(NSTimer * _Nonnull timer) {
        [UIAlertView showAt:[NSString localizedStringForKey:@"GSDK_server_error" value:@"服务器错误"]];
        [self dismissAction];
    } repeats:true];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)reloadAtUrl:(NSString*)urlString {
    self.urlString = urlString;
    NSURLRequest * requst = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
    __weak GSDKWebViewController * weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.webView loadRequest:requst];
    });
}

#pragma mark - Action
- (void)dismissAction {
    [[NSNotificationCenter defaultCenter] postNotificationName:kSetupBadgeNoticationName object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:GSDKToolBarDidFinishNotification object:@NO userInfo:nil];
    [GSDKCOMMONMETHOD.rootViewController.view setUserInteractionEnabled:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)backAction {
    if ([_webView canGoBack]) {
        [_webView goBack];
    } else {
        [self dismissAction];
    }
}

- (void)payBackAction {
    if (self.payState == PayStateCancel) {
        GSDKIAPStatus * iap = [[GSDKIAPStatus alloc] init];
        GSDKErrorStatus * errorS = [[GSDKErrorStatus alloc] init];
        iap.gSDKIAPStatus = GSDK_IAP_STATUS_PRODUCTBUY;
        errorS.gSDKErrorStatus = GSDK_ERROR_STATUS_BUY_ERROR;
        GSDKMessageStatus * message = [[GSDKMessageStatus alloc] init];
        message.code = @"-1";
        message.msg = @"Cancel";
        [[NSNotificationCenter defaultCenter] postNotificationName: GSDKIAPDidFinishNotification object:nil userInfo:@{@"GSDKIAPStatus": iap, @"GSDKErrorStatus": errorS, @"GSDKMessageStatus": message}];
    } else if (self.payState == PayStateFailure) {
        GSDKIAPStatus * iap = [[GSDKIAPStatus alloc] init];
        GSDKErrorStatus * errorS = [[GSDKErrorStatus alloc] init];
        iap.gSDKIAPStatus = GSDK_IAP_STATUS_PRODUCTBUY;
        errorS.gSDKErrorStatus = GSDK_ERROR_STATUS_BUY_ERROR;
        GSDKMessageStatus * message = [[GSDKMessageStatus alloc] init];
        message.code = @"-1";
        message.msg = @"pay failure";
        [[NSNotificationCenter defaultCenter] postNotificationName: GSDKIAPDidFinishNotification object:nil userInfo:@{@"GSDKIAPStatus": iap, @"GSDKErrorStatus": errorS, @"GSDKMessageStatus": message}];
    } else if (self.payState == PayStateSuccess) {
        GSDKIAPStatus * iap = [[GSDKIAPStatus alloc] init];
        GSDKMessageStatus * message = [[GSDKMessageStatus alloc] init];
        iap.gSDKIAPStatus = GSDK_IAP_STATUS_PRODUCTBUY;
        message.code = @"0";
        message.msg = @"pay success";
        [[NSNotificationCenter defaultCenter] postNotificationName:GSDKIAPDidFinishNotification object:nil userInfo:@{@"GSDKIAPStatus": iap, @"GSDKMessageStatus": message}];
    }
    [[GSDKActivityIndicatorView shared] hide];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kSetupBadgeNoticationName object:nil];;
    [GSDKCOMMONMETHOD.rootViewController.view setUserInteractionEnabled:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:GSDKToolBarDidFinishNotification object:@NO userInfo:nil];
}

- (void)payCancelAction {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:[NSString localizedStringForKey:@"GSDK_exitpay_notice" value:@"退出购买界面（购买过程不要退出购买界面）"] preferredStyle: UIAlertControllerStyleAlert];
    @weakify(self)
    [alertController addAction:[UIAlertAction actionWithTitle:[NSString localizedStringForKey:@"GSDK_confirm_text" value:@"确定"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self)
        [self payBackAction];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:[NSString localizedStringForKey:@"GSDK_cancel_text" value:@"取消"] style:UIAlertActionStyleCancel handler: nil]];
    [self presentViewController:alertController animated:true completion:nil];
}

#pragma mark - UIWebView Delegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
    [_aiView startAnimating];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [_aiView stopAnimating];
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    if (self.timer != nil) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
//    NSString * urlString = GSDKCOMMONMETHOD.versionModel.is_purl;
//    if (urlString == nil) { urlString = @"http://139.199.182.68:8837/api/ocean_payment"; }
//    if (![urlString hasSuffix:@"?"]) { urlString = [NSString stringWithFormat:@"%@?", urlString]; }
//    if ([self.urlString rangeOfString:urlString].length > 0) {
//        [UIAlertView showAt:[NSString localizedStringForKey:@"GSDK_server_error" value:@"服务器错误"]];
//        GSDKIAPStatus * iap = [[GSDKIAPStatus alloc] init];
//        iap.gSDKIAPStatus = GSDK_IAP_STATUS_PRODUCTBUY;
//        GSDKErrorStatus * errorS = [[GSDKErrorStatus alloc] init];
//        errorS.gSDKErrorStatus = GSDK_ERROR_STATUS_BUY_ERROR;
//        GSDKMessageStatus * message = [[GSDKMessageStatus alloc] init];
//        message.code = @"-1";
//        message.msg = [NSString localizedStringForKey:@"GSDK_server_error" value:@"服务器错误"];
//        [[NSNotificationCenter defaultCenter] postNotificationName: GSDKIAPDidFinishNotification object:nil userInfo:@{@"GSDKIAPStatus": iap, @"GSDKErrorStatus": errorS, @"GSDKMessageStatus": message}];
//        [[GSDKActivityIndicatorView shared] hide];
//        
//        [[NSNotificationCenter defaultCenter] postNotificationName:kSetupBadgeNoticationName object:nil];;
//        [GSDKCOMMONMETHOD.rootViewController.view setUserInteractionEnabled:YES];
//        [self dismissViewControllerAnimated:YES completion:nil];
//    }
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *urlString = [[request URL] absoluteString];
    NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
    //返回按钮
    if([urlComps count] && [[urlComps objectAtIndex:0]
                            isEqualToString:@"webpop"]) {
        [self backAction];
        return NO;
    }
    //关闭按钮
    if([urlComps count] && [[urlComps objectAtIndex:0]
                            isEqualToString:@"webcancel"]) {
        NSString * urlString = GSDKCOMMONMETHOD.versionModel.is_purl;
        if (urlString == nil || urlString.length == 0) { urlString = @"http://api.zy1game.com/api/ocean_payment"; }
        if (![urlString hasSuffix:@"?"]) { urlString = [NSString stringWithFormat:@"%@?", urlString]; }
        
        if ([self.urlString rangeOfString:urlString].length > 0) {
            [self payBackAction];
        } else {
            [self dismissAction];
        }
        return NO;
    }
    //注销
    if([urlComps count] && [[urlComps objectAtIndex:0]
                            isEqualToString:@"weblogout"]) {
        [self dismissAction];
        
        [GSDKCOMPLATFORM logout];
        return NO;
    }
    //切换账号
    if([urlComps count] && [[urlComps objectAtIndex:0]
                            isEqualToString:@"webSwitchAccount"]) {
        [self dismissAction];
        
        [GSDKCOMPLATFORM switchAccount];
        return NO;
    }
    //支付成功
    if([urlComps count] && [[urlComps objectAtIndex:0]
                            isEqualToString:@"paysuccess"]) {
        self.payState = PayStateSuccess;
        return NO;
    }
    //支付失败
    if([urlComps count] && [[urlComps objectAtIndex:0]
                            isEqualToString:@"payfailure"]) {
        self.payState = PayStateFailure;
        return NO;
    }
    return true;
}

@end
